<script setup lang="ts">
import {onMounted, ref, computed} from "vue";
import request from "../../utils/requests.ts";
import {Search} from "@element-plus/icons-vue";

interface Movie {
  id: number;
  name: string;
  poster: string;
  director: string;
  actors: string;
  release_date: string;
}

let tableData = ref<Movie[]>([])
const searchText = ref('')
const loading = ref(false) // 添加加载状态

async function getMovies() {
  try {
    loading.value = true // 开始加载
    const response = await request.get<Movie[]>('/movies')
    tableData.value = response.data;
  } catch (error) {
    console.log('获取电影数据失败:', error)
  } finally {
    loading.value = false // 无论成功或失败都结束加载
  }
};

// 计算属性：根据搜索文本过滤后的电影数据
const filteredMovies = computed(() => {
  // 如果搜索框为空，则显示所有数据
  if (!searchText.value) {
    return tableData.value;
  }

  // 如果有搜索内容，则过滤数据
  const keyword = searchText.value.toLowerCase();
  return tableData.value.filter(movie =>
      movie.name.toLowerCase().includes(keyword) ||
      movie.director.toLowerCase().includes(keyword) ||
      movie.actors.toLowerCase().includes(keyword)
  );
});

// 组件挂载时获取数据
onMounted(() => {
  getMovies();
});
</script>

<template>
  <h2>Fly影业电影信息管理系统</h2>
  <div style="display: flex;justify-content: space-between">
    <div class="search-container" style="padding-bottom: 20px">
      <el-input
          v-model="searchText"
          placeholder="搜索电影名称、导演或主演"
          class="search-input"
          clearable
      >
        <template #prefix>
          <el-icon>
            <Search/>
          </el-icon>
        </template>
      </el-input>
    </div>
    <el-pagination
        size="small"
        background
        layout="prev, pager, next"
        :total="50"
        class="mt-4"
        style="padding-bottom: 20px"
    />
  </div>
  <!-- 添加加载状态提示 -->
  <div v-if="loading" class="loading-container">
    <el-skeleton :rows="5" animated/>
  </div>

  <!-- 数据加载完成后显示表格 -->
  <div v-else>
    <el-table :data="filteredMovies" style="width: 100%">
      <el-table-column prop="id" label="电影ID"/>
      <el-table-column prop="name" label="电影名称"/>
      <el-table-column label="电影海报">
        <template #default="scope">
          <img
              v-if="scope.row.poster"
              :src="scope.row.poster"
              alt="电影海报"
              style="width: 80px; height: 100px; object-fit: cover;"
          />
          <span v-else>暂无海报</span>
        </template>
      </el-table-column>
      <el-table-column prop="director" label="导演"/>
      <el-table-column prop="actors" label="主演"/>
      <el-table-column prop="release_date" label="上映时间"/>
    </el-table>

    <!-- 当没有数据时显示提示 -->
    <div v-if="filteredMovies.length === 0 && !loading" class="no-data">
      <el-empty description="暂无匹配的电影数据"/>
    </div>
  </div>

</template>

<style scoped>
.search-input {
  width: 300px;
}

.loading-container {
  padding: 20px;
}

.no-data {
  padding: 40px 0;
}
</style>
